package controllers

import (
	"my-go-project/model"
	"my-go-project/utils/token"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 接收的数据结构
type commentSearchJSON struct {
	PassageID int `json:"pa_id"`
}

// 顶级评论信息
type ParentCommentJSON struct {
	CommentuserImg string             `json:"avatar"`            //头像
	Commentuser    string             `json:"username"`          //姓名
	CommentuseID   int                `json:"user_id"`           //用户ID
	CommentID      int                `json:"comment_id"`        //评论ID
	CommentType    int                `json:"comment_type"`      //评论的类型
	CommentContent string             `json:"text"`              //评论内容
	Commentlike    int                `json:"like_count"`        //点赞数量
	IsLike         bool               `json:"is_like"`           //是否点赞
	ChildComment   []ChildCommentJSON `json:"replies,omitempty"` //子评论列表
}
type ChildCommentJSON struct {
	CommentID      int    `json:"comment_id"`     //评论ID
	CommentuserImg string `json:"avatar"`         //头像
	Commentuser    string `json:"username"`       //姓名
	CommentuserID  int    `json:"user_id"`        //用户ID
	CommentType    int    `json:"comment_type"`   //评论的类型
	CommentContent string `json:"text"`           //评论内容
	Replyusername  string `json:"reply_username"` //回复的用户的姓名
	ReplyuserID    int    `json:"reply_user_id"`  //回复的用户的ID
	Commentlike    int    `json:"like_count"`     //点赞数量
	IsLike         bool   `json:"is_like"`        //是否点赞
}

type CommentUpload struct {
	CommentContent string `json:"CommentContent"`
	CommentReplyID int    `json:"CommentReplyID"`
	CommentType    int    `json:"CommentType"`
	ParentID       int    `json:"ParentID"`
	PassageID      int    `json:"PassageID"`
	ReplyUserID    int    `json:"ReplyUserID"`
}

type CommentDelete struct {
	CommentID int `json:"CommentID"`
}

func GetCommentsByPassageID(c *gin.Context) {
	var search commentSearchJSON
	pa_id, err := strconv.Atoi(c.Param("pa_id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求体格式错误错误！",
		})
		return
	}
	search.PassageID = pa_id
	uerID , _ := token.ExtractTokenID(c)
	//返回的评论列表 第一维度顶级评论，第二维度子评论
	var ReturnCommentInfo []ParentCommentJSON
	//TODO: 根据文章的ID查找到该文章下面的所有一级评论信息
	comments, err := model.GetCommentsByPaID(search.PassageID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "查询评论失败！",
		})
		return
	}
	//遍历每一个顶级评论查找下面的子评论
	for _, comment := range comments {
		var R1 ParentCommentJSON
		R1.CommentType = 1
		//先更新顶级评论自身的信息
		User, err := model.GetUserByID(comment.CommentUserID)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": "查询用户信息失败！",
			})
			return
		}
		R1.CommentuseID = User.UserID
		R1.Commentuser = User.UName
		R1.CommentuserImg = User.ProfilePhoto
		R1.CommentContent = comment.CommentContent
		R1.CommentID = comment.CommentID
		//递归查找该评论下面的子评论
		R1.Commentlike, err = model.GetCommentLikeCount(comment.CommentID)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": "查询评论点赞数量失败！",
			})
			return
		}
		R1.IsLike , _= model.GetisLikeComment(comment.CommentID, int(uerID))
		//查找该评论下面的子评论
		commentChildren, err := model.GetChildernComments(comment.CommentID)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": "查询评论子评论失败！",
			})
			return
		}
		for _, childComment := range commentChildren {
			var R2 ChildCommentJSON
			R2.CommentID = childComment.CommentID
			R2.CommentType = childComment.CommentType
			//先更新子评论自身的信息
			R2.CommentContent = childComment.CommentContent
			R2.Commentuser = childComment.CommentUserName
			R2.CommentuserID = childComment.CommentUserID
			R2.CommentuserImg = childComment.CommentUserPhoto
			R2.ReplyuserID = childComment.CommentParentUserID
			R2.Replyusername = childComment.CommentParentUserName
			R2.Commentlike = childComment.CommentLikeCount
			R2.IsLike , _= model.GetisLikeComment(childComment.CommentID, int(uerID))
			R1.ChildComment = append(R1.ChildComment, R2)
		}
		ReturnCommentInfo = append(ReturnCommentInfo, R1)
	}

	c.JSON(http.StatusOK, gin.H{
		"data": ReturnCommentInfo})
}

func UploadComment(ctx *gin.Context) {
	var commentUpload CommentUpload
	if err := ctx.ShouldBindBodyWithJSON(&commentUpload); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "请求体格式错误！！！",
		})
		return
	}

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	comment := model.Comment{
		PassageID:       commentUpload.PassageID,
		CommentUserID:   int(uid),
		CommentContent:  commentUpload.CommentContent,
		CommentType:     commentUpload.CommentType,
		CommentReplyID:  commentUpload.CommentReplyID,
		ParentCommentID: commentUpload.ParentID,
	}

	cid, err := model.UploadComment(comment)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	var str string
	if commentUpload.CommentType == 1 {
		str = "passage_comment"
	} else {
		str = "comment_comment"
	}

	var message model.Message
	if commentUpload.ReplyUserID != 0 {
		message = model.Message{
			PassageID:  commentUpload.PassageID,
			Type:       str,
			SenderID:   int(uid),
			ReceiverID: commentUpload.ReplyUserID,
			CommentID:  cid,
		}
	} else {
		aid, err := model.GetAuthorID(commentUpload.PassageID)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
		message = model.Message{
			PassageID:  commentUpload.PassageID,
			Type:       str,
			SenderID:   int(uid),
			ReceiverID: aid,
			CommentID:  cid,
		}
	}
	if message.SenderID == message.ReceiverID {
		ctx.JSON(http.StatusOK, gin.H{
			"Response": "评论发布成功！",
		})
		return
	}
	_, err = message.SaveMessage()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"Response": "评论发布成功！",
	})
}

func DeleteComment(ctx *gin.Context) {
	var commentID CommentDelete
	if err := ctx.ShouldBindBodyWithJSON(&commentID); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "请求体格式错误！",
		})
		return
	}

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	cid, err := model.GetCommentUserID(commentID.CommentID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	if int(uid) != cid {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": "他人评论无法删除！",
		})
		return
	}

	err = model.DeleteComment(commentID.CommentID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"Response": "评论删除成功！",
	})
}
